package com.sugo.seckill.aop.redis;

import com.sugo.seckill.lock.distributedlock.redis.RedissLockUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @ClassName LockAspect
 * @Description
 * @Author hubin
 * @Date 2021/1/29 23:13
 * @Version V1.0
 **/
@Component
@Scope
@Aspect
@Order(1)
public class LockRedisAspect {


    // 注入request
    @Autowired
    private HttpServletRequest request;


    // service 切入点
    @Pointcut("@annotation(com.sugo.seckill.aop.redis.ServiceRedisLock)")
    public void lockAspect(){

    }

    @Around("lockAspect()")
    public Object around(ProceedingJoinPoint joinPoint){

        // 获取请求参数
        String str = request.getRequestURI();
        String killId = str.substring(str.lastIndexOf("/")-1,str.lastIndexOf("/"));

        Object obj = null;
        // 开始加锁 -- 方法增强
        // 使用redis锁
        boolean res = RedissLockUtil.tryLock("seckill_goods_lock_" + killId,
                TimeUnit.SECONDS,
                3,
                10);
        try {
            //加锁成功，执行业务
            if(res){

                obj = joinPoint.proceed();
            }
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }finally {
            // 释放锁
          if(res){
              RedissLockUtil.unlock("seckill_goods_lock_" + killId);
          }
        }

        return obj;
    }




}

